<?php
namespace Home\Controller;

class ApiController extends CommonAction
{
    public function ApiController()
    {
        parent::__construct();
    }

    protected function _getNavigator($name, $action)
    {
        $navigator = array(
            array(
                'name' => 'Api文档',
                'url' => '/home/api/index'
            ),
            array(
                'name' => $name,
                'url' => $action
            )
        );
        return $navigator;
    }

    public function index()
    {
        $dept = $_SESSION['dept'];
        $userId = $_SESSION['user_id'];
        $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);

        $sql = 'select * from zt_api_cate where isdel=0 and parent_id=0 order by addtime desc';
        $list = M()->query($sql);

        $this->assign('list', $list);
        $this->assign('parentId', 0);
        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator('所有接口分类', '/home/' . $sectionId));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function child_list($parentId)
    {
        $dept = $_SESSION['dept'];
        $userId = $_SESSION['user_id'];
        $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);

        $sql = 'select * from zt_api_cate where isdel=0 and parent_id=' . $parentId . ' order by addtime desc';
        $list = M()->query($sql);

        $this->assign('list', $list);
        $this->assign('parentId', $parentId);
        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator('所有接口分类', '/home/' . $sectionId));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function error_code()
    {
        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator('系统错误码定义规范', '/home/' . $sectionId));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function format()
    {
        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator('对外服务接口的格式', '/home/' . $sectionId));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function get_api_cate($id)
    {
        $sql = 'select * from zt_api_cate where aid=' . $id . ' order by addtime desc';
        $list = M()->query($sql);
        if (!empty($list)) {
            $data = $list[0];
        } else {
            $data = array();
        }
        $res = array(
            'errorCode' => 0,
            'errorMsg' => 'success',
            'data' => $data
        );
        $this->ajaxReturn($res);
    }

    public function save_api_cate()
    {
        $id = $this->_getParam('id', null);
        $name = $this->_getParam('name', null);
        $desc = $this->_getParam('desc', null);
        $parentId = $this->_getParam('parentId', null);
        if (empty($id)) {
            $data = array(
                'cname' => $name,
                'cdesc' => $desc,
                'isdel' => 0,
                'addtime' => time(),
                'parent_id' => $parentId
            );
            $res = M('ApiCate')->add($data);
        } else {
            $data = array(
                'cname' => $name,
                'cdesc' => $desc,
                'isdel' => 0,
                'parent_id' => $parentId
            );
            $res = M('ApiCate')->where('aid=' . $id)->save($data);
        }
        if ($res) {
            $res = array(
                'errorCode' => 0,
                'errorMsg' => '保存成功',
            );
        } else {
            $res = array(
                'errorCode' => -1,
                'errorMsg' => '保存失败',
            );
        }
        $this->ajaxReturn($res);
    }

    public function info($cate_id)
    {
        if (empty($cate_id)) {
            $this->error('请选择接口分类');
        }
        $dept = $_SESSION['dept'];
        $userId = $_SESSION['user_id'];
        $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);

        $sql = 'select * from zt_api_cate where aid=' . $cate_id . ' order by addtime desc';
        $cate = M()->query($sql);

        $this->_getApiMenu($cate_id);

        $sql = "SELECT
                api.id,
                aid,
                num,
                url,
                name,
                des,
                parameter,
                raw_param,
                memo,
                re,
                lasttime,
                lastuid,
                type,
                zu.realname
            FROM
                zt_api AS api
            LEFT JOIN zt_user AS zu ON api.lastuid = zu.id
            WHERE
                aid = " . $cate_id . "
            AND api.isdel = 0
            ORDER BY
                ord DESC,
                api.id DESC";
        $list = M()->query($sql);
        $this->assign('list', $list);

        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator($cate[0]['cname'], '/home/' . $sectionId . '?cate_id=' . $cate_id));
        $this->assign('section', $sectionId);
        $this->display();
    }

    private function _getApiMenu($cate_id)
    {
        $sql = "SELECT
                *
            FROM
                zt_api
            WHERE
                aid = " . $cate_id . "
            AND isdel = 0
            ORDER BY
                ord DESC,
                id DESC";
        $menu = M()->query($sql);
        $this->assign('menu', $menu);
    }

    public function add_page($cate_id)
    {
        if (empty($cate_id)) {
            $this->error('请选择接口分类');
        }
        $dept = $_SESSION['dept'];
        $userId = $_SESSION['user_id'];
        $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);

        $this->_getApiMenu($cate_id);

        $sql = 'select * from zt_api_cate where aid=' . $cate_id . ' order by addtime desc';
        $cate = M()->query($sql);

        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator($cate[0]['cname'], '/home/api/info?cate_id=' . $cate_id));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function add($cate_id)
    {
        if (empty($cate_id)) {
            $this->error('请选择接口分类');
        }
        $num = htmlspecialchars($_POST['num'], ENT_QUOTES);   //接口编号(为了导致编号的前导0去过滤掉。不用用I方法过滤)
        $name = $_POST['name'];  //接口名称
        $memo = $_POST['memo']; //备注
        $des = $_POST['des'];    //描述
        $type = $_POST['type'];  //请求方式
        $url = $_POST['url'];

        $paramType = $_POST['paramType'][0];

        if ($paramType == 'raw') {
            $parameter = '';
            $rawParam = $_POST['raw_param'];
        } else {
            $parameter = serialize($_POST['p']);
            $rawParam = '';
        }

        $re = $_POST['re'];  //返回值
        $lasttime = time(); //最后操作时间
        $lastuid = $_SESSION['user_id']; //操作者id
        $isdel = 0; //是否删除的标识
        $data = array(
            'aid' => $cate_id,
            'num' => $num,
            'name' => $name,
            'des' => $des,
            'url' => $url,
            'type' => $type,
            'parameter' => $parameter,
            'raw_param' => $rawParam,
            're' => $re,
            'lasttime' => $lasttime,
            'lastuid' => $lastuid,
            'isdel' => $isdel,
            'memo' => $memo,
            'ord' => 99999,
        );
        $re = M('Api')->add($data);
        if ($re) {
            redirect('/home/api/info?cate_id=' . $cate_id, 3, '接口添加成功！页面跳转中...');
        } else {
            $this->error('接口添加失败！');
        }
    }

    public function edit_page($cate_id, $id)
    {
        if (empty($cate_id)) {
            $this->error('请选择接口分类');
        }
        $dept = $_SESSION['dept'];
        $userId = $_SESSION['user_id'];
        $dept = D('Dept', 'Service')->getSpecialUserDept($userId, $dept);

        $this->_getApiMenu($cate_id);

        $sql = 'select * from zt_api_cate where aid=' . $cate_id . ' order by addtime desc';
        $cate = M()->query($sql);

        //得到数据的详情信息start
        $sql = "select * from zt_api where id='{$id}' and aid='{$cate_id}'";
        $res = M()->query($sql);
        //得到数据的详情信息end
        if (!empty($res)) {
            $info = $res[0];
            $info['parameter'] = unserialize($info['parameter']);
            $count = count($info['parameter']['name']);
            $p = array();
            for ($i = 0; $i < $count; $i++) {
                $p[$i]['name'] = $info['parameter']['name'][$i];
                $p[$i]['type'] = $info['parameter']['type'][$i];
                $p[$i]['default'] = $info['parameter']['default'][$i];
                $p[$i]['des'] = $info['parameter']['des'][$i];
            }
            $info['parameter'] = $info['parameter'];
            $this->assign('info', $info);
        }

        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator($cate[0]['cname'], '/home/api/info?cate_id=' . $cate_id));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function edit($cate_id)
    {
        $id = $_POST['id'];   //接口id
        $num = htmlspecialchars($_POST['num'], ENT_QUOTES);   //接口编号(为了导致编号的前导0去过滤掉。不用用I方法过滤)
        $name = $_POST['name'];  //接口名称
        $memo = $_POST['memo']; //备注
        $des = $_POST['des'];    //描述
        $type = $_POST['type'];  //请求方式
        $url = $_POST['url']; //请求地址

        $paramType = $_POST['paramType'][0];
        if ($paramType == 'raw') {
            $parameter = '';
            $rawParam = $_POST['raw_param'];
        } else {
            $parameter = serialize($_POST['p']);
            $rawParam = '';
        }
        $re = $_POST['re'];  //返回值
        $lasttime = time(); //最后操作时间
        $lastuid = $_SESSION['user_id']; //操作者id
        $username = $_SESSION['username']; //操作者

        $data = array(
            'num' => $num,
            'name' => $name,
            'des' => $des,
            'url' => $url,
            'type' => $type,
            'parameter' => $parameter,
            'raw_param' => $rawParam,
            're' => $re,
            'lasttime' => $lasttime,
            'lastuid' => $lastuid,
            'memo' => $memo,
        );
        $re = M('Api')->where('id=' . $id)->save($data);

        if ($re) {
            // 发钉钉 阿宁01605848136212
            if ($cate_id == 97) {
                D('Dingding', 'Service')->sendTextMsg('000010', $username . '修改了接口【' . $name . '】,地址:' . 'http://superb.360cec.com/home/api/info?cate_id=' . $cate_id . '#info_api_' . md5($id));
            }
            redirect('/home/api/info?cate_id=' . $cate_id . '#info_api_' . md5($id), 3, '接口修改成功！页面跳转中...');
        } else {
            $this->error('接口修改失败！');
        }
    }
}
